/* eslint-disable no-unused-vars */
import { log } from '@/common/utils'
import { mapState, mapActions, mapMutations } from 'vuex'
import {
  getAdvertisingBannerList,
  getNewAdvertisingBannerList,
} from '@/api/public/public'

export default {
  data: function () {
    return {
      go: false,
      adImgList: [],
      adImg: null,
      ignoreLoginPathArr: ['product/product', 'product/list'],
    }
  },
  computed: {
    ...mapState('user', ['token', 'hasLogin', 'address']),
  },
  filters: {
    // 脱敏 手机号
    hideName(val) {
      let newStr = ''
      if (val != undefined && val.length > 0) {
        if (val) {
          const reg = /^1\d{10}$/
          if (reg.test(val)) {
            newStr = val.toString()
            return newStr.slice(0, 3) + '****' + newStr.slice(-4)
          } else {
            return val
          }
        }
      } else {
        return ''
      }
    },
    // 限制长度
    limitLength(str) {
      return str.length > 5 ? str.slice(0, 5) + '...' : str
    },
    // 处理数值
    focusNum(num) {
      if (!num) return 0
      let newNum = null
      if (num >= 100000000) {
        return (newNum = (num / 100000000).toFixed(1) + '亿')
      } else if (num >= 10000 && num < 100000000) {
        return (newNum = (num / 10000).toFixed(1) + '万')
      } else {
        return num
      }
    },
    // 处理数值
    salesNum(num) {
      let newNum = null
      if (num < 100) {
        return '小于100'
      } else if (num >= 100 && num < 10000) {
        return (newNum = (num / 10000).toFixed(1) + '万')
      } else {
        return (newNum = (num / 100000000).toFixed(1) + '亿')
      }
    },
    // 计算年龄
    filterAge(val) {
      let newTime = new Date().getFullYear()
      let oldTime = new Date(val).getFullYear()
      return newTime - oldTime
    },
    // 处理金额
    price(value) {
      if (value != undefined && value != null) {
        if (value >= 10000) {
          var v = (value / 10000).toFixed(2) + '万'
          return v
        }
      }
      return value
    },
    // 处理点赞、评论、收藏显示
    filterZan(num) {
      if (!num) return 0
      if (num < 999) {
        return num
      } else {
        return '999﹢'
      }
    },
  },
  methods: {
    ...mapActions('user', ['getLocalHos']),
    ...mapMutations('user', ['SET_ADDRESS']),

    // 处理时间格式T
    dataFormat(input) {
      if (input) {
        var dt = new Date(input)
        var y = dt.getFullYear()
        var m = (dt.getMonth() + 1).toString().padStart(2, '0')
        var d = dt.getDate().toString().padStart(2, '0')
        if (input.toLowerCase() === 'yyyy-mm-dd') {
          return `${y}-${m}-${d}`
        } else {
          var hh = dt.getHours().toString().padStart(2, '0')
          var mm = dt.getMinutes().toString().padStart(2, '0')
          var ss = dt.getSeconds().toString().padStart(2, '0')
          return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
        }
      }
    },

    handContent(item) {
      return item.replace(/<[^>]+>/g, '') //去掉所有的html标记
    },
   
    // 打电话
    callPhone(phone) {
      uni.makePhoneCall({
        phoneNumber: phone,
        fail: err => {
          console.log(err)
        },
      })
    },

    // 拷贝
    copyTxt(txt) {
      uni.setClipboardData({
        data: txt,
        showToast: false,
        success: () => {
          uni.$u.toast('复制成功')
        },
      })
    },

    // 图片预览
    previewImage(url, index = 0) {
      let urls = []
      if (Array.isArray(url)) {
        urls = url
      } else {
        urls.push(url)
      }
      uni.previewImage({
        current: index,
        urls: urls,
      })
    },

    // 是否登录认证
    async isHasLogin() {
      console.log("uni.getStorageSync('Token')", uni.getStorageSync('Token'))
      if (uni.getStorageSync('Token') != '') {
        return true
      } else {
        setTimeout(() => {
          uni.navigateTo({
            url: '/packageAuth/pages/authorization/index',
          })
        }, 50)
        return false
      }
    },
    // 跳转
    async toPage(path, isLogin = true, type = 0, callback) {
      if (!path) {
        uni.$u.toast('敬请期待~')
        return
      }
      if (!path.includes('package')) path = '/pages/' + path
      if (this.go) return
      try {
        if (isLogin) {
          let result = await this.isHasLogin()
          if (!result) return
          // console.log('xxxxxx没被return',this.isHasLogin())
        }
        this.go = true
        let fun = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
        uni[fun[type]]({
          // url: '/pages/' + path,
          url: path,
          complete: () => {
            this.go = false
            if (callback) callback()
          },
        })
      } catch (e) {
        log(e)
      }
    },

    //返回
    back(val, callback) {
      let o = {
        success: callback,
      }
      if (typeof val == 'number') {
        o.delta = val
      } else {
        o.url = val
      }
      if (!this.$prePage()) {
        this.toPage('index/index')
      }
      uni.navigateBack(o)
    },
    openMap(lng, lat, name) {
      uni.openLocation({
        latitude: lat,
        longitude: lng,
        name: name,
      })
    },
    //省市区截取
    getAreaBystr(str) {
      let area = {}
      let index11 = 0
      let index1 = str.indexOf('省')
      if (index1 == -1) {
        index11 = str.indexOf('自治区')
        if (index11 != -1) {
          area.province = str.substring(0, index11 + 3)
        } else {
          area.province = str.substring(0, 0)
        }
      } else {
        area.province = str.substring(0, index1 + 1)
      }

      let index2 = str.indexOf('市')
      if (index11 == -1) {
        area.city = str.substring(index11 + 1, index2 + 1)
      } else {
        if (index11 == 0) {
          area.city = str.substring(index1 + 1, index2 + 1)
        } else {
          area.city = str.substring(index11 + 3, index2 + 1)
        }
      }

      let index3 = str.lastIndexOf('区')
      if (index3 == -1) {
        index3 = str.indexOf('县')
        area.district = str.substring(index2 + 1, index3 + 1)
      } else {
        area.district = str.substring(index2 + 1, index3 + 1)
      }
      return area
    },
    //合并uni.getLocation和uni.chooseLocation两个api返回的数据
    mergeAddress(addressByGet, addressByChoose) {
      let temAddress = this.getAreaBystr(addressByChoose.address)
      let newAddress = JSON.parse(JSON.stringify(addressByGet))
      if (newAddress) {
        newAddress.latitude = addressByChoose.latitude
        newAddress.longitude = addressByChoose.longitude
        newAddress.poiName = addressByChoose.name
        newAddress.province = temAddress.province
        newAddress.city = temAddress.city
        ;(newAddress.district = temAddress.district),
          (newAddress.street = ''),
          (newAddress.streetNum = '')
      } else {
        newAddress = {
          latitude: addressByChoose.latitude,
          longitude: addressByChoose.longitude,
          poiName: addressByChoose.name,
          province: temAddress.province,
          city: temAddress.city,
          district: temAddress.district,
          street: '',
          streetNum: '',
        }
      }
      return newAddress
    },
    //首页及医疗tabbar页更换位置信息
    toPositionIndex() {
      return new Promise((resolve, reject) => {
        this.toGetPosition().then(() => {
          // this.toPage('position/index')
          //地图选择地址
          uni.chooseLocation({
            latitude: this.address ? this.address.latitude : null,
            longitude: this.address ? this.address.longitude : null,
            success: data => {
              // this.addressData.address = data.name;
              console.log(
                '获取位置data',
                data.address,
                this.address,
                this.getAreaBystr(data.address)
              )
              let address = this.mergeAddress(this.address, data)
              this.SET_ADDRESS(address)
              resolve()
            },
          })
        })
      })
    },
    //定位前置判断权限逻辑处理
    toGetPosition() {
      return new Promise((resolve, reject) => {
        console.log('token', this.token)
        if (this.token) {
          console.log('去检查定位权限-----', this.address)
          // checkLocationPermission()
          //   .then(() => {
          resolve()
          if (!this.address) {
            uni.getLocation({
              type: 'gcj02',
              geocode: true,
              success: res => {
                console.error('获取位置信息成功', res)
                this.SET_ADDRESS({
                  ...res.address,
                  latitude: res.latitude,
                  longitude: res.longitude,
                })
                this.getLocalHos()
              },
            })
          }
          // })
          // .catch(() => {
          //   console.log('2222222走到这里--------------')
          //   uni.showModal({
          //     title: '无法访问您的位置',
          //     content: '当前无定位访问权限，建议前往设置',
          //     confirmText: '前往设置',
          //     success(e) {
          //       if (e.confirm) {
          //       }
          //     },
          //   })
          //   // uni.getLocation({
          //   //   type: 'gcj02',
          //   //   geocode: true,
          //   //   isHighAccuracy: true,
          //   //   success: res => { },
          //   // })
          // })
        } else {
          resolve()
        }
      })
    },
    // 个页面banner图获取
    // 广告
    getAderList(catalog) {
      getAdvertisingBannerList({
        catalog: catalog,
        pageNum: 1,
        pageSize: 100,
        pageEnable: 0,
      }).then(res => {
        this.adImg = res.list && res.list.length ? res.list[0] : ''
      })
    },
    // 广告List
    getAderImgList(catalog) {
      getAdvertisingBannerList({
        catalog: catalog,
        pageNum: 1,
        pageSize: 100,
        pageEnable: 0,
      }).then(res => {
        this.adImgList = res.list ? res.list : []
      })
    },
  },
}
